//
//  RCSearchAllCityVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-6-26.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCSearchAllCityVC.h"
#import "IManager.h"
#import "IManager+SearchAllCity.h"
#import "RCSearchAllCityTagDataModel.h"
#import "RCMerchantListVC.h"
#import "GloableEngineService.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "NSArray+EX.h"
#import "RCSearchMoreTagsVC.h"

#define kTextBGImageFile             @"image_about_textBG.png"
#define kDistrictImageFile           @"image_allCity_district.png"
#define kCategoryImageFile           @"image_allCity_category.png"

@interface RCSearchAllCityVC ()

@property (nonatomic, retain) RCSearchAllCityTagDataModel *dataModel;
@property (nonatomic,retain) MBProgressHUDEx *progressHub;
@property (nonatomic,assign) CGFloat districtViewHeight;
@property (nonatomic,assign) int64_t requestID;

@end

@implementation RCSearchAllCityVC
@synthesize dataModel = _dataModel;
@synthesize progressHub = _progressHub;
@synthesize requestID = _requestID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)dealloc{
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.dataModel = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"搜全城";
    self.navigationItem.titleView = [self createTitleView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.districtViewHeight = 0.0;
	// Do any additional setup after loading the view.
    [self refreshData];
 
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma
#pragma mark ServerData ----下拉刷新数据

-(void) refreshData
{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    NSString *cityID = [GloableEngineService sharedInstance].selectedCityID;
    _requestID = [[IManager sharedInstance] requestSearchTagListAtCity:cityID withDelegate:self];
}



#pragma
#pragma mark IManage Delegate
-(void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        self.dataModel = (RCSearchAllCityTagDataModel*)dataModel;
        [self createDistrictView];
        [self createCategoryView];
    }
    
    
}

-(void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
    }
    
}

#pragma mark createTagsView

-(void)createDistrictView{
    if (nil == self.dataModel && self.dataModel.districtTags && [self.dataModel.districtTags count] > 0) {
        return;
    }
    
    UIImageView *districtImageView = [[UIImageView alloc]initWithFrame:CGRectMake(14,20, 8, 10)];
    districtImageView.backgroundColor = [UIColor clearColor];
    NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kDistrictImageFile];
    [districtImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
    [self.viewContainer addSubview:districtImageView];
    [districtImageView release];
    
    UILabel *districtLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 17, 150, 13)];
    districtLabel.backgroundColor = [UIColor clearColor];
    districtLabel.textColor = [UIColor colorWithHex:0xff505050];
    districtLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:13];
    districtLabel.text = @"热门商区";
    [self.viewContainer addSubview:districtLabel];
    [districtLabel release];
    
    _districtViewHeight = 38;
    
    UIImageView *districtBGImageView = [[UIImageView alloc]init];
    districtBGImageView.backgroundColor = [UIColor clearColor];
    districtBGImageView.userInteractionEnabled = YES;
    
    
    for (int i = 0; i <= [self.dataModel.districtTags count]; i++) {
        NSString *tagName = @"";
        CGFloat width = 73;
        if (i == [self.dataModel.districtTags count]) {
            tagName = @"更多商区";
            if (i % 4 != 3) {
                width = width*2;
            }
        }else{
            RCTagItem *item = [self.dataModel.districtTags safeObjectAtIndex:i];
            tagName = item.tagName;
        }
        UILabel *tagLabel = [[UILabel alloc]initWithFrame:CGRectMake(i%4*73, 33*(i/4)+10, width, 13)];
        tagLabel.backgroundColor = [UIColor clearColor];
        tagLabel.textColor = [UIColor colorWithHex:0xff505050];
        tagLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:13];
        tagLabel.text = tagName;
        tagLabel.textAlignment = UITextAlignmentCenter;
        [districtBGImageView addSubview:tagLabel];
        [tagLabel release];
        
        UIButton *tagButton = [[UIButton alloc]initWithFrame:CGRectMake(i%4*73, 33*(i/4), width, 33)];
        tagButton.backgroundColor = [UIColor clearColor];
        tagButton.tag = 100 + i;
        [tagButton addTarget:self action:@selector(tagButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [districtBGImageView addSubview:tagButton];
        [tagButton release];
    }
    
    NSInteger lineCount = ceil(([self.dataModel.districtTags count]+1)/4.0);
    CGFloat districtHeight = lineCount * 33;
    districtBGImageView.frame = CGRectMake(14, _districtViewHeight, 292, districtHeight);
    NSString *textBGFilePath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:kTextBGImageFile];
    UIImage *textBGImage = [UIImage imageWithContentsOfFile:textBGFilePath];
    textBGImage = [textBGImage resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [districtBGImageView setImage:textBGImage];
    
    _districtViewHeight +=districtHeight;
    
    NSInteger lastOneIndex = 0;
    lastOneIndex =  [self.dataModel.districtTags count] % 4;
    for (int i= 0; i < 3; i++) {
        CGFloat lineHeight = districtHeight;
        if (lastOneIndex   == i) {
            lineHeight -= 33;
        }
        CGFloat xPos = 70+73*i;
        UIView *verticleLine = [[UIView alloc]initWithFrame:CGRectMake(xPos, 0, 1, lineHeight)];
        verticleLine.backgroundColor = [UIColor colorWithHex:0xffeaeaea];
        [districtBGImageView addSubview:verticleLine];
        [verticleLine release];
    }
    for (int i=32; i<districtHeight-5; i+=33) {
        UIView *horizonLine = [[UIView alloc]initWithFrame:CGRectMake(0, i, 292, 1)];
        horizonLine.backgroundColor = [UIColor colorWithHex:0xffe6e6e6];
        [districtBGImageView addSubview:horizonLine];
        [horizonLine release];
    }
    
    [self.viewContainer addSubview:districtBGImageView];
    [districtBGImageView release];
}


-(void)createCategoryView{
    if (nil == self.dataModel && self.dataModel.categorieTags && [self.dataModel.categorieTags count] > 0) {
        return;
    }
    
    _districtViewHeight +=25;
    
    UIImageView *categoryImageView = [[UIImageView alloc]initWithFrame:CGRectMake(14,_districtViewHeight+3, 8, 10)];
    categoryImageView.backgroundColor = [UIColor clearColor];
    NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kCategoryImageFile];
    [categoryImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
    [self.viewContainer addSubview:categoryImageView];
    [categoryImageView release];
    
    UILabel *categoryLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, _districtViewHeight, 150, 13)];
    categoryLabel.backgroundColor = [UIColor clearColor];
    categoryLabel.textColor = [UIColor colorWithHex:0xff505050];
    categoryLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:13];
    categoryLabel.text = @"热门分类";
    [self.viewContainer addSubview:categoryLabel];
    [categoryLabel release];
    
    _districtViewHeight +=25;
    
    UIImageView *categoryBGImageView = [[UIImageView alloc]init];
    categoryBGImageView.backgroundColor = [UIColor clearColor];
    categoryBGImageView.userInteractionEnabled = YES;
    

    for (int i = 0; i <= [self.dataModel.categorieTags count]; i++) {
        NSString *tagName = @"";
        CGFloat width = 73;
        if (i == [self.dataModel.categorieTags count]) {
            if (i % 4 != 3) {
                width = width*2;
            }
            tagName = @"更多分类";
        }else{
            RCTagItem *item = [self.dataModel.categorieTags safeObjectAtIndex:i];
            tagName = item.tagName;
        }
        
        UILabel *tagLabel = [[UILabel alloc]initWithFrame:CGRectMake(i%4*73, 33*(i/4)+10, width, 13)];
        tagLabel.backgroundColor = [UIColor clearColor];
        tagLabel.textColor = [UIColor colorWithHex:0xff505050];
        tagLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:13];
        tagLabel.text = tagName;
        tagLabel.textAlignment = UITextAlignmentCenter;
        [categoryBGImageView addSubview:tagLabel];
        [tagLabel release];
        
        UIButton *tagButton = [[UIButton alloc]initWithFrame:CGRectMake(i%4*73, 33*(i/4), width, 33)];
        tagButton.backgroundColor = [UIColor clearColor];
        tagButton.tag = 200 + i;
        [tagButton addTarget:self action:@selector(tagButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [categoryBGImageView addSubview:tagButton];
        [tagButton release];
    }
    
    NSInteger lineCount = ceil(([self.dataModel.categorieTags count]+1)/4.0);
    CGFloat districtHeight = lineCount * 33;
    categoryBGImageView.frame = CGRectMake(14, _districtViewHeight, 292, districtHeight);
    NSString *textBGFilePath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:kTextBGImageFile];
    UIImage *textBGImage = [UIImage imageWithContentsOfFile:textBGFilePath];
    textBGImage = [textBGImage resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [categoryBGImageView setImage:textBGImage];
    
    _districtViewHeight +=districtHeight;
    

    NSInteger lastOneIndex = 0;
    lastOneIndex =  [self.dataModel.categorieTags count] % 4;
    for (int i= 0; i < 3; i++) {
        CGFloat lineHeight = districtHeight;
        if (lastOneIndex   == i) {
            lineHeight -= 33;
        }
        CGFloat xPos = 70+73*i;
        UIView *verticleLine = [[UIView alloc]initWithFrame:CGRectMake(xPos, 0, 1, lineHeight)];
        verticleLine.backgroundColor = [UIColor colorWithHex:0xffeaeaea];
        [categoryBGImageView addSubview:verticleLine];
        [verticleLine release];
    }
    
    for (int i=32; i<districtHeight-5; i+=33) {
        UIView *horizonLine = [[UIView alloc]initWithFrame:CGRectMake(0, i, 292, 1)];
        horizonLine.backgroundColor = [UIColor colorWithHex:0xffe6e6e6];
        [categoryBGImageView addSubview:horizonLine];
        [horizonLine release];
    }
    
    [self.viewContainer addSubview:categoryBGImageView];
    [categoryBGImageView release];
}

-(void)tagButtonClicked:(id)sender{
    UIButton *button = (UIButton *)sender;
    NSInteger tag = button.tag;
    if (tag >= 200) {
        NSInteger index = tag - 200;
        NSInteger count = [self.dataModel.categorieTags count];
        if (index == count) {
            RCSearchMoreTagsVC *vc = [[RCSearchMoreTagsVC alloc]initWithParameters:[GloableEngineService sharedInstance].selectedCityID WithType:SearchMoreTagsVCTypeCategory];
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }else{
            RCTagItem *item = [self.dataModel.categorieTags objectAtIndex:index];
            RCMerchantListVC *vc = [[RCMerchantListVC alloc] initWithMerchantType:item.tagName withMerchantID:item.tagID];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }
    }else{
        NSInteger index = tag - 100;
        NSInteger count = [self.dataModel.districtTags count];
        if (index == count) {
            RCSearchMoreTagsVC *vc = [[RCSearchMoreTagsVC alloc]initWithParameters:[GloableEngineService sharedInstance].selectedCityID WithType:SearchMoreTagsVCTypeDistrict];
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }else{
            RCTagItem *item = [self.dataModel.districtTags objectAtIndex:index];
            RCMerchantListVC *vc = [[RCMerchantListVC alloc] initWithDistrictType:item.tagName withDistrictID:item.tagID];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }
    }
}


#pragma mark 更多的tag被点击
-(void) rcSearchMoreTagsClick:(NSString *)tag
{
    RCMerchantListVC *listVC = [[RCMerchantListVC alloc] init];
    [self.navigationController pushViewController:listVC animated:YES];
    [listVC release];
}
@end
